package com.ease.web.server;

import java.util.List;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ease.common.vo.Endpoint;

//import com.sun.jmx.mbeanserver.JmxMBeanServer;

public class JbossEndpointDetector extends ServerEndpointDetector {

	private static final transient Log log = LogFactory.getLog(JbossEndpointDetector.class);

	// protocol: AJP/1.3 HTTP/1.1
	// scheme: http
	// HostName: jboss.system->type=ServerInfo->MBean Attribute=HostName
	public Endpoint get(String protocol, String scheme) {

		List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);

		MBeanServer mbeanServer = null;
		if (mbeanServers.size() > 0) {
			for (MBeanServer ibeanServer : mbeanServers) {
				if (getServerType().equals(ibeanServer.getDefaultDomain())) {
					mbeanServer = ibeanServer;
					break;
				}
			}
		}

		if (mbeanServer == null) {
			return null;// throw new IllegalStateException("MBeanServer not found");
		}

		String objectNameFilter = getObjectNameFilter();
		try {

			Set<ObjectName> objectNames = mbeanServer.queryNames(new ObjectName(objectNameFilter), null);

			for (ObjectName objectName : objectNames) {
				String protocolAttribute = asString(mbeanServer.getAttribute(objectName, "protocol"));
				String schemeAttribute = asString(mbeanServer.getAttribute(objectName, "scheme"));

				if (protocol.equals(protocolAttribute) && scheme.equals(schemeAttribute)) {
					int port = asInt(mbeanServer.getAttribute(objectName, "port"));
					String address = asString(mbeanServer.getAttribute(objectName, "address"));
					Endpoint endpoint = new Endpoint();
					endpoint.setAddress(null != address && address.startsWith("/") ? address.substring(1) : address);
					endpoint.setPort(port);

					return endpoint;
				}
			}

		} catch (Exception e) {
			log.error("objectNameFilter=" + objectNameFilter, e);
		}
		log.error("endpoint not found, objectNameFilter=" + objectNameFilter);

		return null;
	}

	protected String getObjectNameFilter() {
		return "jboss.web:type=Connector,*";
	}

	protected String getServerType() {
		return "jboss";
	}

}
